import request from '@/axios'
import { useUserStoreWithOut } from '@/store/modules/user'

// 获取所有平台列表（下拉框用）
export const getPlatformsApi = () => {
  return request.get<string[]>({
    url: '/api/ai/platforms'
  })
}
export function getIsStreamApi(platform: string) {
  return request.get({
    url: 'api/ai/isStream',
    params: { platform }
  })
}
// 发送非流式对话请求
export const chatWithAiApi = (data: { platform: string; prompt: string; sessionId: string }) => {
  return request.post({ url: '/api/ai/chat', data })
}

// 清空会话（可选扩展）
export const clearSessionApi = (sessionId: string) => {
  return request.post({
    url: '/api/ai/session/clear',
    data: { sessionId }
  })
}
// 获取会话
export const streamChatApi = (params: {
  platform: string
  sessionId: string
  messages: { role: string; content: string }[]
}): EventSource => {
  const userStore = useUserStoreWithOut()
  const Authorization = 'Bearer ' + userStore.getToken

  const query = new URLSearchParams({
    platform: params.platform,
    sessionId: params.sessionId,
    messages: JSON.stringify(params.messages),
    Authorization
  }).toString()

  return new EventSource(`/api/ai/stream?${query}`)
}

// 保存消息记录
export function saveMessageApi(data: {
  sessionId: string
  platform: string
  role: string
  content: string
}) {
  return request.post({
    url: '/api/ai/message/save',
    data
  })
}

// 获取历史聊天记录
export function getMessagesApi(sessionId: string) {
  return request.get({
    url: '/api/ai/messages/page',
    params: { sessionId }
  })
}
// 会话分页
export function getSessionPageApi(page = 1, size = 20) {
  return request.get({ url: '/api/ai/session/page', params: { page, size } })
}

// 消息分页
export function getMessagePageApi(sessionId: string, page = 1, size = 50) {
  return request.get({ url: '/api/ai/message/page', params: { sessionId, page, size } })
}
// 保存会话（用于 startNewSession 调用）
export function saveSessionApi(data: { sessionId: string; title: string; platform: string }) {
  return request.post({
    url: '/api/ai/session/save',
    data
  })
}
